package com.jialiang.email.server.impl;

import com.jialiang.email.server.IEmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Date;

@Slf4j
@Component
public class EmailServiceImpl implements IEmailService {

    public EmailServiceImpl() {
        log.debug("创建发送邮件的服务对象: EmailServiceImpl");
    }

    @Autowired(required = false)
    private JavaMailSender javaMailSender;

    /**
     * 邮箱正则表达式
     */
    private static final String EMAIL_REGEX =
            "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^-]+(?:\\.[a-zA-Z0-9_!#$%&'*+/=?`{|}~^-]+)*@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$";

    /**
     * 邮箱标题
     */
    @Value("${spring.mail.title}")
    private String title;

    /**
     * 发件人邮箱
     */
    @Value("${spring.mail.username}")
    private String username;

    @Override
    public void sendEmail(String email, String subject, String content) {
        validateEmail(email);
        if (subject == null || subject.isEmpty()){
            subject = "你没有写邮件标题这是默认的邮件标题";
        }
        if (content == null || content.isEmpty()){
            content = "你没有写邮件内容这是一条默认的邮件内容";
        }
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setSubject(subject);
            helper.setFrom(new InternetAddress(username, title));
            helper.setTo(email);
            helper.setSentDate(new Date());
            helper.setText(content);
            javaMailSender.send(message);
            log.debug("邮件发送成功");
        } catch (MailException | MessagingException | UnsupportedEncodingException e) {
            log.error("邮件发送失败" + e.getMessage());
        }
    }

    @Override
    public void sendEmail(String email) {
        sendEmail(email,null,null);
    }

    private static void validateEmail(String email) throws IllegalArgumentException {
        if (email == null || !email.matches(EMAIL_REGEX) ||email.isEmpty()) {
            throw new IllegalArgumentException("无效的电子邮件地址: " + email);
        }
    }
}